package com.ruoyi.project.common.utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.project.cms.domain.WxSubscribeMsg;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SubscribeMsgUtils {
    @Autowired
    private WxMaService wxMaStationService;
    @Autowired
    private WxMaService wxMaMemberService;
    @Autowired
    private WxMaService wxMaDriverService;

    /**
     * 订阅消息模板
     * data对应参数格式要正确，注意字段规定长度
     */
    public void sendMsgTemplate(String openId, WxSubscribeMsg wsm){
        WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
        wxMaSubscribeMessage.setToUser(openId);
        wxMaSubscribeMessage.setTemplateId(wsm.getTemplateId());
        wxMaSubscribeMessage.setPage(wsm.getPage());
        if(ObjectUtil.isNotEmpty(wsm.getKeyword1())){
            wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(wsm.getKeyword1(),wsm.getValue1()));
        }
        if(ObjectUtil.isNotEmpty(wsm.getKeyword2())){
            wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(wsm.getKeyword2(),wsm.getValue2()));
        }
        if(ObjectUtil.isNotEmpty(wsm.getKeyword3())){
            wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(wsm.getKeyword3(),wsm.getValue3()));
        }
        if(ObjectUtil.isNotEmpty(wsm.getKeyword4())){
            wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(wsm.getKeyword4(),wsm.getValue4()));
        }
        if(ObjectUtil.isNotEmpty(wsm.getKeyword5())){
            wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(wsm.getKeyword5(),wsm.getValue5()));
        }
        try {
            switch (wsm.getType()){
                case 1:
                    //会员
                    wxMaMemberService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
                    break;
                case 2:
                    //司机
                    wxMaDriverService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
                    break;
                case 3:
                    break;
                case 4:
                    //检测站
                    wxMaStationService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
                    break;
                default:
                    break;
            }
        }catch (WxErrorException wx){
            wx.getError();
        }
    }

}
